package com.pangu.core.engine.game.task.poker;

import java.util.List;

import org.cache2k.expiry.ValueWithExpiryTime;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ActionTaskUtils;
import com.pangu.core.engine.game.BeiMiGameEvent;
import com.pangu.core.engine.game.BeiMiGameTask;
import com.pangu.core.engine.game.task.AbstractTask;
import com.pangu.util.GameUtils;
import com.pangu.util.rules.model.Board;
import com.pangu.util.rules.model.NiuniuPosition;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUserClient;

import lombok.extern.slf4j.Slf4j;

/**
  * @ClassName: BeginTask
  * @Description:  开始德州游戏
  * @author 老王
  * @date 2018年3月27日 下午4:09:49
  *
  */
@Slf4j
public class PokerBeginTask  extends AbstractTask implements ValueWithExpiryTime  , BeiMiGameTask{
	
	@Override
	public void execute() {
		
		/*******更新状态，通知前端 end*******/
		//1.获取到玩家
		List<PlayUserClient> playerList = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(), orgi) ;
		//2.这个时候返回了洗好的牌
		Board board = GameUtils.playGame(playerList, gameRoom, gameRoom.getLastwinner(), gameRoom.getCardsnum());
		// 3.保存牌局
		CacheHelper.getBoardCacheBean().put(gameRoom.getId(), board, gameRoom.getOrgi());
		//4.更新player为playing
		for(Object temp : playerList){
			PlayUserClient playerUser = (PlayUserClient) temp ;
			playerUser.setGamestatus(BMDataContext.GameStatusEnum.PLAYING.toString());
			if(CacheHelper.getApiUserCacheBean().getCacheObject(playerUser.getId(), playerUser.getOrgi())!=null){
				CacheHelper.getApiUserCacheBean().put(playerUser.getId(), playerUser, orgi);
			}
			
		}
		//5.发牌，得到该用户的2张牌，发送到前端去。
		NiuniuPosition[] po = board.getNiuniuPosition();
		for (NiuniuPosition niuniuPosition : po) {
			if(niuniuPosition.getPlayer()!=null)
			{
				niuniuPosition.setCommand(BMDataContext.BEIMI_GAME_LASTHANDS);
				ActionTaskUtils.sendEvent(BMDataContext.BEIMI_GAME_LASTHANDS, niuniuPosition.getPlayer(),niuniuPosition);	
			}
		}
		//6.3秒钟后开始进行打牌
		super.getGame(gameRoom.getPlayway(), orgi).change(gameRoom , BeiMiGameEvent.AUTO.toString() , 3);
		log.info("2秒后开始下注");
	}
	
	private long timer  ;
	private GameRoom gameRoom = null ;
	private String orgi ;
	
	public PokerBeginTask(long timer , GameRoom gameRoom, String orgi){
		super();
		this.timer = timer ;
		this.gameRoom = gameRoom ;
		this.orgi = orgi ;
	}
	@Override
	public long getCacheExpiryTime() {
		return System.currentTimeMillis()+timer*1000;	//5秒后执行
	}
	
	
}
